package com.haoshuang.zhouzhoubang.ui.page.settled.facerecognition

import android.Manifest
import android.content.Context
import android.os.Bundle
import com.alipay.face.api.ZIMFacade
import com.alipay.face.api.ZIMFacadeBuilder
import com.haoshuang.zhouzhoubang.databinding.ActivityFaceRecognitionBinding
import com.haoshuang.zhouzhoubang.model.event.RefreshHomeData
import com.haoshuang.zhouzhoubang.model.event.RefreshTeamUserInfo
import com.haoshuang.zhouzhoubang.ui.activity.AgreementActivity
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.LogUtil
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import java.util.HashMap


/**
 *  人脸识别
 */
class FaceRecognitionActivity :
    BaseVMActivity<FaceRecognitionViewModel, ActivityFaceRecognitionBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<FaceRecognitionActivity>()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        ZIMFacade.install(this)

        binding.titleBar.title = "人脸识别"
        binding.titleBar.leftImageView().click { finish() }

        binding.tvStart.clickWithTrigger {
            PermissionHelper.requestPermission(
                mActivity,
                "权限使用说明",
                "用于帮您实现实名认证, 人脸识别",
                Manifest.permission.CAMERA,
            ) {

                if (it) {
                    val metaInfos = ZIMFacade.getMetaInfos(mActivity)
                    val name = AccountUtils.user?.user_name
                    val idNumber = AccountUtils.user?.id_card
                    vm.getFaceParams(name, idNumber, metaInfos)
                } else {
                    toast("请开启相机权限")
                }
            }
        }

    }

    override fun initData() {

    }

    override fun startObserve() {

        vm.getFaceParamsData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                verify(it?.data?.certifyId ?: "")
            }
        }

        vm.faceRecognitionCallbackData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                startPage<AgreementActivity>()
                LiveEventBus.get(RefreshTeamUserInfo::class.java).post(RefreshTeamUserInfo)
                LiveEventBus.get(RefreshHomeData::class.java).post(RefreshHomeData)
                finish()
            }
        }
    }


    /**
     * 开始人脸识别
     * @param certifyID String
     */
    private fun verify(certifyID: String) {
        val extParams = HashMap<String, String>()
        //如需指定活体检测UI界面方向(横屏+竖屏)，请指定这一项。
        extParams.put(
            ZIMFacade.ZIM_EXT_PARAMS_KEY_SCREEN_ORIENTATION,
            ZIMFacade.ZIM_EXT_PARAMS_VAL_SCREEN_PORT
        )
        //如需支持活体视频返回，请指定这一项，并在response.videoFilePath中获取视频本地路径。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_USE_VIDEO] =
            ZIMFacade.ZIM_EXT_PARAMS_VAL_USE_VIDEO_TRUE
        //如需设置OCR的“下一步”按钮颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_OCR_BOTTOM_BUTTON_COLOR] = "#FF0000"
        //如需自定义活体检测页面的进度条颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_FACE_PROGRESS_COLOR] = "#FF0000"
        val zimFacade = ZIMFacadeBuilder.create(this)
        zimFacade.verify(certifyID, true, extParams) { response ->
            if (1000 == response.code) {
                toast("认证成功")
                vm.faceRecognitionCallback()
            } else {
                LogUtil.debugInfo("认证失败${response.code}")
            }
            true
        }
    }

}